package easy;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class Solution_671 {

    private boolean flag = false;
    private int minSecond = Integer.MAX_VALUE;
    public int findSecondMinimumValue(TreeNode root) {
        dps(root, root.val);
        return flag ? minSecond : -1;
    }

    private void dps(TreeNode node, int val) {
        if (node.left == null) {
            return;
        }
        if (node.left.val == val) {
            if (node.right.val != val) {
                minSecond = Math.min(minSecond, node.right.val);
                flag = true;
            }
            dps(node.left, val);
        }
        if (node.right.val == val) {
            if (node.left.val != val) {
                minSecond = Math.min(minSecond, node.left.val);
                flag = true;
            }
            dps(node.right, val);
        }
    }

    public static void main(String[] args) {
        Solution_671 model = new Solution_671();
        // [1, 1,3, 1,1,3,4, 3,1,1,1,3,8,4,8, 3,3,1,6,2,1]
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(1);
        root.right = new TreeNode(3);

        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(1);
        root.right.left = new TreeNode(3);
        root.right.right = new TreeNode(4);

        root.left.left.left = new TreeNode(3);
        root.left.left.right = new TreeNode(1);
        root.left.right.left = new TreeNode(1);
        root.left.right.right = new TreeNode(1);
        root.right.left.left = new TreeNode(3);
        root.right.left.right = new TreeNode(8);
        root.right.right.left = new TreeNode(4);
        root.right.right.right = new TreeNode(8);

        root.left.left.left.left = new TreeNode(3);
        root.left.left.left.right = new TreeNode(3);

        root.left.left.right.left = new TreeNode(1);
        root.left.left.right.right = new TreeNode(6);
        root.left.right.left.left = new TreeNode(2);
        root.left.right.left.right = new TreeNode(1);
        System.out.println(model.findSecondMinimumValue(root));
        System.out.println(Integer.MAX_VALUE);
    }

    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
}
